package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.PageResult;
import com.itheima.constant.QueryPageBean;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.SetmealDao;
import com.itheima.pojo.Setmeal;
import com.itheima.utils.DateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
   @Autowired
    public SetmealDao setmealDao;

   @Autowired
   private JedisPool jedisPool;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private MemberDao memberDao;


   @Autowired  //spring容器注入freemarkerConfig
    private FreeMarkerConfigurer freeMarkerConfigurer;

   @Value("${out_put_path}")  //从freemarker.perproties中取值
   private  String out_Put_Path;
    /**
     * 添加套餐
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        setsetmealAndcheckgroup(setmeal, checkgroupIds);
//        将图片名称保存到redis中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

//        添加数据后 添加静态页面
       generateMobileStaticHtml();
    }

//    生成当前的方法的静态页面
    public void generateMobileStaticHtml(){
        List<Setmeal> list = setmealDao.findAll();

      //生成套餐的静态页面方法
        generateSetmaelHtml(list);

        //生成套餐详情的静态页面方法
        generateSetmaelDetailHtml(list);
    }


    public  void  generateSetmaelHtml(List<Setmeal> list){
        Map map=new HashMap<>();
        map.put("setmealList",list);
        generateHtml("mobile_setmeal.ftl","mobile_setmeal.html",map);
    }

    public  void  generateSetmaelDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map=new HashMap();
            map.put("setmeal",setmealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl",
                    "mobile_setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

//    用于生成静态模板页面
    public  void  generateHtml(String teplateName,String htmlPageName,Map map){
        //获取配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter fileWriter=null;
        try {
            // /获取模板配置对象
            Template template = configuration.getTemplate(teplateName);
            //  构造输出流
            fileWriter = new FileWriter(new File(out_Put_Path + "/" + htmlPageName));
            // 输出文件
            template.process(map,fileWriter);
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 分页条件查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal>page=setmealDao.findByString(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 查询所有的套餐
     * 数据返回到移动端
     * @return list
     */
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    @Override
    public Map<String, Object> getBusinessReportData() throws Exception {

        //报表日期
        String today = DateUtils.parseDate2String(DateUtils.getToday());
        //获得本周一日期   一周
        String thisWeekMonday = DateUtils.parseDate2String(DateUtils.getThisWeekMonday());
        //获得本月第一天日期   一月
        String firstDay4ThisMonth = DateUtils.parseDate2String(DateUtils.getFirstDay4ThisMonth());



        //本日新增会员数
        Integer todayNewMember = memberDao.findMemberCountByDate(today);
        //本周新增会员数
        Integer thisWeekNewMember = memberDao.findMemberCountByWeek(thisWeekMonday);
        //总会员数
        Integer totalMember = memberDao.findMemberTotalCount();
        //本月新增会员数
        Integer thisMonthNewMember = memberDao.findMemberCountByWeek(firstDay4ThisMonth);


        //今日预约数
        Integer todayOrderNumber = orderDao.findOrderCountByDate(today);
        //本周预约数
        Integer thisWeekOrderNumber = orderDao.findOrderCountAfterDate(thisWeekMonday);
        //本月预约数
        Integer thisMonthOrderNumber = orderDao.findOrderCountAfterDate(firstDay4ThisMonth);
        //今日到诊数
        Integer todayVisitsNumber = orderDao.findVisitsCountByDate(today);
        //本周到诊数
        Integer thisWeekVisitsNumber = orderDao.findVisitsCountAfterDate(thisWeekMonday);
        //本月到诊数
        Integer thisMonthVisitsNumber = orderDao.findVisitsCountAfterDate(firstDay4ThisMonth);
        //热门套餐查询
        List<Map> hotSetmeal = orderDao.findHotSetmeal();
        Map<String,Object> result = new HashMap<>();
        result.put("reportDate",today);
        result.put("todayNewMember",todayNewMember);
        result.put("totalMember",totalMember);
        result.put("thisWeekNewMember",thisWeekNewMember);
        result.put("thisMonthNewMember",thisMonthNewMember);
        result.put("todayOrderNumber",todayOrderNumber);
        result.put("thisWeekOrderNumber",thisWeekOrderNumber);
        result.put("thisMonthOrderNumber",thisMonthOrderNumber);
        result.put("todayVisitsNumber",todayVisitsNumber);
        result.put("thisWeekVisitsNumber",thisWeekVisitsNumber);
        result.put("thisMonthVisitsNumber",thisMonthVisitsNumber);
        result.put("hotSetmeal",hotSetmeal);
        return result;
    }

    /**
     * 绑定套餐和检查组多对多关系
     * @param setmeal
     * @param checkgroupIds
     */
    public void setsetmealAndcheckgroup(Setmeal setmeal, Integer[] checkgroupIds) {
        Map<String,Integer> map=new HashMap<>();
        map.put("setmeal_id",setmeal.getId());
        if (checkgroupIds!=null&&checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                map.put("checkgroup_id",checkgroupId);
                setmealDao.setsemealAndcheckGroup(map);
            }
        }
    }
}
